<template>
    <view class="wifiPage">
        <view
            style="
                justify-content: center;
                display: flex;
                flex-direction: column;
                align-items: center;
                width: 100%;
                height: 100%;
            "
        >
            <view v-if="status == 0" class="middle_view">
                <label class="title_label">请拿手机站在秤上</label>
                <image class="device_img" src="https://smosun-minapp.oss-cn-shanghai.aliyuncs.com/weapp/img/binding_logo.png"></image>
                <image class="status_img" src="https://smosun-minapp.oss-cn-shanghai.aliyuncs.com/weapp/img/bing_icon.png"></image>
                <label class="status_label">配网中…</label>
            </view>
            <view v-if="status == 1" class="middle_view">
                <label class="title_label">{{ errorMessage }}</label>
                <image class="device_img" src="https://smosun-minapp.oss-cn-shanghai.aliyuncs.com/weapp/img/reconnect_logo.png"></image>
                <image class="status_img" src="https://smosun-minapp.oss-cn-shanghai.aliyuncs.com/weapp/img/reconnect_icon.png"></image>
                <view @click="reDiscovery()" class="reconnect_btn">再试一次</view>
            </view>
            <view v-if="status == 2" class="middle_view">
                <label class="title_label">配网成功！</label>
                <image class="device_img" src="https://smosun-minapp.oss-cn-shanghai.aliyuncs.com/weapp/img/bind_success_logo.png"></image>
                <image class="status_img" src="https://smosun-minapp.oss-cn-shanghai.aliyuncs.com/weapp/img/bind_success_icon.png"></image>
                <label class="status_label">配网成功</label>
            </view>
        </view>
        <u-popup
            :show="modalVisible"
            mode="center"
            :round="15"
            :safeAreaInsetBottom="false"
            :closeOnClickOverlay="false"
        >
            <view class="modalContent">
                <text class="modalTitle">配网超时</text>
                <text class="modalText">请检查</text>
                <text class="modalText">1、WiFi名称、密码是否正确</text>
                <text class="modalText">2、WiFi是否单独2.4G频率</text>
                <text class="modalText">3、路由器是否正常联网</text>
                <view class="closeBtn" @click="modalClose"> 确定 </view>
            </view>
        </u-popup>
    </view>
</template>

<script>
import { mapState } from "vuex";
import uploadWeight from "../../mixin/uploadWeight";

export default {
    mixins: [uploadWeight],
    data() {
        return {
            balance: {},
            status: 0, //0 1 2
            errorMessage: "",
            sendCount: 0,
            ssid: "",
            password: "",
            countDownCount: 60,
            countDownTimer: null,
            modalVisible: false,
        };
    },
    computed: {
        ...mapState(["connectDeviceInfo", "userInfo"]),
    },
    watch: {
        // 监听蓝牙设备
        "$store.state.devicesList": {
            immediate: true,
            deep: true,
            handler(e) {
                if (e.length > 0 && this.connectDeviceInfo.name != "倾小体") {
                    e.forEach((item) => {

                        if (item.name == "倾小体" && this.balance.deviceId != item.deviceId) {
                            this.$store
                                .dispatch("stopBluetoothDevicesDiscovery")
                                .then((res) => {})
                                .catch((err) => {});
                            this.balance = item;

                            this.connectBlue(this.balance);
                        }
                    });
                }
            },
        },
    },
    methods: {
        async connectBlue(item) {
            var that = this;
            if (item.isconnect) {
                return;
            }
            try {
                await this.$store.dispatch("createBLEConnection", item);
                this.setWifi(item);
            } catch (err) {
                console.log('connectBlue',err);
            }
        },
        async setWifi(deviceInfo) {
            var res = await this.$store.dispatch("getProperti", {
                deviceId: deviceInfo.deviceId,
                properti: "write",
            });
            this.balance = Object.assign(deviceInfo, res);


            this.configWifi();
            // this.notifyBLEConnectionStateChange();
        },

        async configWifi() {
            const kBLE_SEND_MAX_LEN = 16;
            var totalPackage = [];
            var totalHex = [];
            var ssidLen = this.ssid.length;
            var ssidArr = [];
            for (let i = 0; i < ssidLen; i += kBLE_SEND_MAX_LEN) {
                if (i + kBLE_SEND_MAX_LEN < ssidLen) {
                    ssidArr.push(this.ssid.substr(i, kBLE_SEND_MAX_LEN));
                } else {
                    ssidArr.push(this.ssid.substr(i, ssidLen - i));
                }
            }
            var passwordLen = this.password.length;
            var passwordArr = [];
            for (let i = 0; i < passwordLen; i += kBLE_SEND_MAX_LEN) {
                if (i + kBLE_SEND_MAX_LEN < passwordLen) {
                    passwordArr.push(this.password.substr(i, kBLE_SEND_MAX_LEN));
                } else {
                    passwordArr.push(this.password.substr(i, passwordLen - i));
                }
            }

            ssidArr.forEach((item, index) => {
                let packageHexStr =
                    "0a" +
                    this.dec2hex(ssidArr.length, 2) +
                    this.dec2hex(index, 2) +
                    this.dec2hex(ssidLen, 2) +
                    this.strToHexCharCode(item);
                packageHexStr += this.chk8xor(packageHexStr);

                var packageBuffer = this.convertHexStrToData(packageHexStr);
                totalHex.push(packageHexStr);
                totalPackage.push(packageBuffer);
            });

            passwordArr.forEach((item, index) => {
                let packageHexStr =
                    "0b" +
                    this.dec2hex(passwordArr.length, 2) +
                    this.dec2hex(index, 2) +
                    this.dec2hex(passwordLen, 2) +
                    this.strToHexCharCode(item);
                packageHexStr += this.chk8xor(packageHexStr);

                var packageBuffer = this.convertHexStrToData(packageHexStr);
                totalHex.push(packageHexStr);
                totalPackage.push(packageBuffer);
            });
            totalHex.push("0e");
            totalPackage.push(this.convertHexStrToData("0e"));
            this.notifyValueChange();
            this.writeBLE(totalPackage, totalHex);
        },
        writeBLE(totalPackage, totalHex) {
            let subPackage = totalPackage[this.sendCount];
            // let dataView = new DataView(subPackage);
            // let senddata = totalHex[this.sendCount];
            // const count = Math.ceil(senddata.length / 2);

            // for (let i = 0; i < count; i++) {
            //     console.log('curCharCode', senddata.substr(i * 2, 2), totalHex);
            //     let curCharCode = parseInt(senddata.substr(i * 2, 2), 16);
            //     dataView.setUint8(i, curCharCode);
            // }
            uni.writeBLECharacteristicValue({
                deviceId: this.balance.deviceId,
                characteristicId: this.balance.characteristicId,
                serviceId: this.balance.serviceId,
                value: subPackage,
                success: (e) => {

                    this.sendCount++;
                    if (this.sendCount >= totalPackage.length) {
                        this.sendCount = 0;
                    } else {
                        this.writeBLE(totalPackage, totalHex);
                    }
                },
                fail(err) {
                    that.errorMessage = "配网失败";
                    that.stopCountDown();
                },
            });
        },
        async notifyValueChange() {
            const res = await this.$store.dispatch("getProperti", {
                deviceId: this.balance.deviceId,
                properti: "notify",
            });
            uni.notifyBLECharacteristicValueChange({
                deviceId: this.balance.deviceId,
                serviceId: res.serviceId,
                characteristicId: res.characteristicId,
                state: true,
                type: "notification",
                complete: (res) => {

                    uni.onBLECharacteristicValueChange((res) => {
                        let characteristicValue = this.ab2hex(res.value);
                        if (characteristicValue.indexOf("cf") != 0) {
                            if (characteristicValue.indexOf("06") >= 0 && characteristicValue.indexOf("06") <= 4) {
                                this.status = 2;
                                uni.showToast({
                                    title: "配网成功",
                                });
                                this.saveWifi(characteristicValue);

                                uni.offBLECharacteristicValueChange();
                            } else if (this.status != 2) {
                                this.status = 1;
                            }
                            this.stopCountDown();
                        }
                        if (characteristicValue.length !== 40) {
                            this.getWeight(res.value);
                        }

                    });
                },
            });
        },
        // async notifyBLEConnectionStateChange() {
        // 	uni.onBLEConnectionStateChange((res) => {
        // 		this.balance.isconnect = res.connected;
        // 		if (res.connected == false && res.deviceId == this.balance.deviceId) {
        // 			this.connectBlue(this.balance);
        // 		}
        // 	});
        // },
        saveWifi(myHex) {
            console.log('myHex',myHex)
            uni.request({
                url: "https://tzc.ximusen.cn/smosun/wifi/mini/saveWifiGroup",
                data: {
                    sn: this.hex2Str(myHex.substr(2)),
                    uid: this.userInfo.uid,
                },
                method: "POST",
                success(res){
                    console.log('success',res)
                    setTimeout(()=>{
                        uni.switchTab({ url: `/pages/home/home` })
                    },2000)
                },
                fail(fail){
                    console.log('fail',fail)
                },
                complete(complete){
                    console.log('complete',complete)
                }
            });
        },
        reDiscovery() {
            this.balance = {};
            this.status = 0;
            this.$store
                .dispatch("startBluetoothDevicesDiscovery")
                .then((res) => {})
                .catch((err) => {});
        },
        dec2hex(dec, len) {
            //10进制转16进制补0
            var hex = "";
            while (dec) {
                var last = dec & 15;
                hex = String.fromCharCode((last > 9 ? 55 : 48) + last) + hex;
                dec >>= 4;
            }
            if (len) {
                while (hex.length < len) hex = "0" + hex;
            }
            return hex;
        },
        strToHexCharCode(str) {
            if (str === "") return "";
            var hexCharCode = [];
            for (var i = 0; i < str.length; i++) {
                hexCharCode.push(str.charCodeAt(i).toString(16));
            }
            return hexCharCode.join("");
        },
        convertHexStrToData(hex) {
            var typedArray = new Uint8Array(
                hex.match(/[\da-f]{2}/gi).map(function (h) {
                    return parseInt(h, 16);
                }),
            );
            return typedArray.buffer;
        },
        addZero(str) {
            return str.length == 1 ? "0" + str : str;
        },
        splitHex(hex) {
            return hex.match(/[\da-f]{2}/gi);
        },
        ab2hex(buffer) {
            let hexArr = Array.prototype.map.call(new Uint8Array(buffer), (bit) => {
                return ("00" + bit.toString(16)).slice(-2);
            });
            return hexArr.join("");
        },
        hex2Str(hexCharCodeStr) {
            var trimedStr = hexCharCodeStr.trim();
            var rawStr = trimedStr.substr(0, 2).toLowerCase() === "0x" ? trimedStr.substr(2) : trimedStr;
            var len = rawStr.length;
            if (len % 2 !== 0) {
                alert("Illegal Format ASCII Code!");
                return "";
            }
            var curCharCode;
            var resultStr = [];
            for (var i = 0; i < len; i = i + 2) {
                curCharCode = parseInt(rawStr.substr(i, 2), 16); // ASCII Code Value
                resultStr.push(String.fromCharCode(curCharCode));
            }
            return resultStr.join("");
        },
        // 异或校验
        chk8xor(hex) {
            var bcc = 0;
            var xor = 0;
            var hexarr = this.splitHex(hex);
            for (var i = 0; i < hexarr.length; i++) {
                var hexint = parseInt(hexarr[i], 16);
                if (i == 0) {
                    xor = hexint;
                } else {
                    bcc = xor ^ hexint;

                    xor = bcc;
                }
            }
            return this.addZero(bcc.toString(16));
        },
        str2ab(str) {
            var buf = new ArrayBuffer(str.length);
            var bufView = new Uint16Array(buf);
            for (var i = 0, strLen = str.length; i < strLen; i++) {
                bufView[i] = str.charCodeAt(i);
            }
            return buf;
        },
        /** 开始倒计时 */
        startCountDown() {

            this.countDownTimer = setTimeout(() => {

                uni.offBLECharacteristicValueChange();
                this.modalVisible = true;
            }, this.countDownCount * 1000);
        },
        /** 停止倒计时 */
        stopCountDown() {

            clearTimeout(this.countDownTimer);
            this.countDownTimer = null;
        },
        modalClose() {
            this.modalVisible = false;
            uni.navigateBack();
        },
    },
    onLoad(option) {
        this.ssid = option.ssid;
        this.password = option.password;
        if (this.connectDeviceInfo.name == "倾小体") {

            this.setWifi(this.connectDeviceInfo);
        } else {
            this.$store
                .dispatch("startBluetoothDevicesDiscovery")
                .then((res) => {})
                .catch((err) => {});
        }
        this.startCountDown();
    },
    onUnload() {
        this.$store
            .dispatch("stopBluetoothDevicesDiscovery")
            .then((res) => {})
            .catch((err) => {});
        this.stopCountDown();
    },
};
</script>

<style scoped>
.wifiPage {
    width: 100vw;
    height: 100vh;
}

.modalContent {
    display: flex;
    flex-direction: column;
    padding: 40rpx;
    font-size: 32rpx;
}

.modalTitle {
    margin-bottom: 24rpx;
    text-align: center;
}

.modalText {
    font-size: 28rpx;
    line-height: 42rpx;
}

.closeBtn {
    padding-top: 30rpx;
    font-size: 32rpx;
    text-align: center;
    color: #418170;
}

.middle_view {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100%;
}

.title_label {
    color: #333333;
    font-size: 36rpx;
}

.device_img {
    height: 668rpx;
    width: 100%;
}

.status_img {
    margin-top: 94rpx;
    width: 112rpx;
    height: 112rpx;
}

.status_label {
    margin-top: 34rpx;
    color: #418170;
    font-size: 34rpx;
}

.reconnect_btn {
    width: 328rpx;
    height: 96rpx;
    border-radius: 24rpx;
    border: 2rpx solid #418170;
    line-height: 96rpx;
    text-align: center;
    color: #418170;
    font-size: 30rpx;
    margin-top: 40rpx;
}
</style>
